#include "app.h"

CApp::CApp():m_TaskManager(0)
			,m_DataStream(0)
			,m_DataDeal(0)
			,m_Service(0){

}

CApp::~CApp(){
	if(m_TaskManager)
		delete m_TaskManager;
	if(m_DataStream)
		delete m_DataStream;
	if(m_DataDeal)
		delete m_DataDeal;
	if(m_Service)
		delete m_Service;
}

void CApp::initialize(){
	m_TaskManager = new CTaskManager;
	m_TaskManager->initialize();
	m_DataStream = new CDataStream;
	m_DataStream->initialize();
	m_DataDeal = new CDataDeal;
	m_DataDeal->initialize(m_DataStream);
	m_Service = new CService;
	m_Service->initialize(m_DataStream);
}

void CApp::run(){
	start();
}

void CApp::execute(){
	XMLNode  child;
	for(;;){
		m_TaskManager->run();

		m_DataDeal->run();
		Sleep(10000);

		m_Service->run();
		while((m_Service->is_running())||(m_DataDeal->is_running())){
			Sleep(500000);
		}

		EnterCriticalSection(&m_cs);
		m_AppNode = m_AppNode.openFileHelper(m_FileName, "SV");
		int j = 0;
		j = m_AppNode.nChildNode();
		if(j){
			for(int i = 0; i < j; ++i){
				child = m_AppNode.getChildNode(i);
				m_TaskManager->new_task((char *)(child.getText()));
			}
		}
		m_AppNode.deleteNodeContent();
		m_AppNode= m_AppNode.createXMLTopNode("SV");
		m_AppNode.writeToFile(m_FileName);
		LeaveCriticalSection(&m_cs);
	}
}

void CApp::newTask(char * n_Task){
	XMLNode  child;
	EnterCriticalSection(&m_cs);
	m_AppNode = m_AppNode.openFileHelper(m_FileName, "SV");
	child =	m_AppNode.addChild("task");
	child.addText(n_Task);
	m_AppNode.writeToFile(m_FileName);
	LeaveCriticalSection(&m_cs);
}